package flc.ast.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.VibrateUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import flc.ast.Constant;
import flc.ast.R;
import flc.ast.adapter.WishAdapter;
import flc.ast.bean.WishBean;
import flc.ast.databinding.FragmentFishBinding;
import flc.ast.utils.AudioPlayer;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.AssetUtil;
import stark.common.basic.utils.FastClickUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FishFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FishFragment extends BaseNoModelFragment<FragmentFishBinding> {

    public static int type = 0;
    private WishAdapter wishAdapter;
    private Animation mZoomAnimation;//动画->木鱼缩放
    private TextView mTvShowContent;
    private int mNumber = 0;
    private boolean isAuto = false;
    private Dialog mySelModeDialog;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isAuto) {
                clickWoodenFish();
                int interval = SPUtils.getInstance().getInt(Constant.TOUCH_INTERVAL_KEY, 1);
                handler.postDelayed(this, interval * 1000);
            }
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.fragment_fish;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mZoomAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_small_big);

        mDataBinding.rvWishList.setLayoutManager(new LinearLayoutManager(mContext));
        wishAdapter = new WishAdapter();
        mDataBinding.rvWishList.setAdapter(wishAdapter);
        wishAdapter.setOnItemClickListener(this);

        mDataBinding.llFishMode.setOnClickListener(this);
        mDataBinding.ivWoodenFish.setOnClickListener(this);
        mDataBinding.tvReset.setOnClickListener(this);
        mDataBinding.llVoice.setOnClickListener(this);
        mDataBinding.llAuto.setOnClickListener(this);
        //选择模式弹窗
        selModeDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivWoodenFish://敲木鱼
                clickWoodenFish();
                break;
            case R.id.tvReset://重置
                mNumber = 0;
                mDataBinding.tvCount.setText("0");
                break;
            case R.id.llVoice://声音
                boolean hasVoice = SPUtils.getInstance().getBoolean(Constant.VOICE_KEY, true);
                hasVoice = !hasVoice;
                SPUtils.getInstance().put(Constant.VOICE_KEY, hasVoice);
                if (hasVoice) {
                    mDataBinding.ivVoice.setImageResource(R.drawable.aicon_sy);
                } else {
                    mDataBinding.ivVoice.setImageResource(R.drawable.aicon_sy2);
                }
                break;
            case R.id.llAuto://自动
                isAuto = !isAuto;
                if (isAuto) {
                    startAlwaysOrTimesTask();
                } else {
                    stopAlwaysAndTimesTask();
                }
                break;
            case R.id.llFishMode://选择模式
                mySelModeDialog.show();
                break;
            case R.id.ivMode1://功德模式
                type = 0;
                setType();
                mySelModeDialog.dismiss();
                break;
            case R.id.ivMode2://心愿模式
                type = 1;
                setType();
                mySelModeDialog.dismiss();
                break;
            case R.id.ivMode3://呼吸模式
                type = 2;
                setType();
                mySelModeDialog.dismiss();
                break;
            case R.id.ivMode4://冥想模式
                type = 3;
                setType();
                mySelModeDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (FastClickUtil.isFastClick()) return;
        View itemView = mDataBinding.rvWishList.getChildAt(position);
        wishAdapter.getItem(position).setNum(wishAdapter.getItem(position).getNum() + 1);
        TextView num = itemView.findViewById(R.id.tvWishItemNum);
        wishAdapter.notifyItemChanged(position);
        num.setTextSize(33);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                num.setTextSize(18);
            }
        }, 500);
    }

    @Override
    protected void initData() {
        mDataBinding.tvCount.setText("0");
        boolean hasVoice = SPUtils.getInstance().getBoolean(Constant.VOICE_KEY, true);
        if (hasVoice) {
            mDataBinding.ivVoice.setImageResource(R.drawable.aicon_sy);
        } else {
            mDataBinding.ivVoice.setImageResource(R.drawable.aicon_sy2);
        }
        getData();
        setType();
        getWoodenFishIconData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setType();
            getWoodenFishIconData();
        }else {
            stopAlwaysAndTimesTask();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void clickWoodenFish() {
        PlayMusic();
        randomAnimation();
        mNumber += 1;
        mDataBinding.ivWoodenFish.post(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCount.setText(mNumber + "");
            }
        });
    }

    public void startAlwaysOrTimesTask() {
        isAuto = true;
        mDataBinding.ivAuto.setImageResource(R.drawable.aicon_zd);
        mDataBinding.ivWoodenFish.setEnabled(false);
        int interval = SPUtils.getInstance().getInt(Constant.TOUCH_INTERVAL_KEY, 1);
        handler.postDelayed(runnable, interval * 1000);
    }

    public void stopAlwaysAndTimesTask() {
        isAuto = false;
        // 移除待处理的 Runnable
        handler.removeCallbacks(runnable);
        mDataBinding.ivWoodenFish.setEnabled(true);
        mDataBinding.ivAuto.setImageResource(R.drawable.aicon_zd2);
    }

    private void PlayMusic() {
        mDataBinding.ivWoodenFish.startAnimation(mZoomAnimation);//缩放动画
        List<String> woodenFish = AssetUtil.getFilePaths(mContext, "woodenFish");
        int musicToneIndex = SPUtils.getInstance().getInt(Constant.MUSIC_TONE_KEY, 0);
        boolean hasVoice = SPUtils.getInstance().getBoolean(Constant.VOICE_KEY, true);
        if (hasVoice) {
            AudioPlayer.getInstance().startVoice(mContext, woodenFish.get(musicToneIndex));
        }
    }

    /**
     * 点击木鱼之后 随机数来提供x横坐标，横坐标需要根据自己屏幕的大小进行预计算
     * 比如：我点击木鱼后，文字屏幕上方的中间点的位置是（800,0）,那么想要实现左右曲线轨迹，可以取值在700~ 1000r
     * 我在这里取巧了，可以自己尝试封装一个更合理的随机数方法来提供值，毕竟switch显得太冗长了
     */
    private void randomAnimation() {
        Random random = new Random();//随机数函数
        int state = random.nextInt(10);
        switch (state) {
            case 0:
                PlayAnimation(0f);
                break;
            case 1:
                PlayAnimation(50f);
                break;
            case 2:
                PlayAnimation(100f);
                break;
            case 3:
                PlayAnimation(200f);
                break;
            case 4:
                PlayAnimation(600f);
                break;
            case 5:
                PlayAnimation(650f);
                break;
            case 6:
                PlayAnimation(400f);
                break;
            case 7:
                PlayAnimation(450f);
                break;
            case 8:
                PlayAnimation(550f);
                break;
            case 9:
                PlayAnimation(700f);
                break;
            case 10:
                PlayAnimation(880f);
                break;
            default:
                break;
        }
    }

    private void randomAnimationFloat(RelativeLayout relativeLayout, TextView textView) {
        Random random = new Random();//随机数函数
        int state = random.nextInt(10);
        switch (state) {
            case 0:
                PlayAnimationFloat(0f, relativeLayout, textView);
                break;
            case 1:
                PlayAnimationFloat(50f, relativeLayout, textView);
                break;
            case 2:
                PlayAnimationFloat(100f, relativeLayout, textView);
                break;
            case 3:
                PlayAnimationFloat(200f, relativeLayout, textView);
                break;
            case 4:
                PlayAnimationFloat(600f, relativeLayout, textView);
                break;
            case 5:
                PlayAnimationFloat(650f, relativeLayout, textView);
                break;
            case 6:
                PlayAnimationFloat(400f, relativeLayout, textView);
                break;
            case 7:
                PlayAnimationFloat(450f, relativeLayout, textView);
                break;
            case 8:
                PlayAnimationFloat(550f, relativeLayout, textView);
                break;
            case 9:
                PlayAnimationFloat(700f, relativeLayout, textView);
                break;
            case 10:
                PlayAnimationFloat(880f, relativeLayout, textView);
                break;
            default:
                break;
        }
    }

    /**
     * 根据对应的很坐标执行动画
     *
     * @param state
     */
    private void PlayAnimationFloat(float state, RelativeLayout relativeLayout, TextView textView) {
        relativeLayout.addView(textView = new TextView(getContext()));//动态添加view
        String selLabel = SPUtils.getInstance().getString(Constant.FLOAT_CHAR_KEY, getString(R.string.merits_add_tips));
        if (selLabel.equals(getString(R.string.empty_text))) {
            textView.setText("");
        } else {
            textView.setText(selLabel);
        }
        int fontAlpha = SPUtils.getInstance().getInt(Constant.FONT_TYPE, 100);
        textView.setAlpha(fontAlpha * 0.01f);
        textView.setTextSize(36);
        textView.setTextColor(Color.WHITE);
        AnimatorSet animSet = new AnimatorSet();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(textView, "translationX", 1000, state);//移动到屏幕中间
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(textView, "translationY", 880f, 0f);//从木鱼移动到上端
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(textView, "alpha", 1f, 0f);//透明度变化
        AnimatorSet.Builder builder = animSet.play(anim2);
        builder.with(anim1).with(anim2).with(anim3);
        animSet.setDuration(3500);//持续时间
        animSet.start(); // 开始播放属性动画
    }

    /**
     * 根据对应的很坐标执行动画
     *
     * @param state
     */
    private void PlayAnimation(float state) {
        mDataBinding.rlAll.addView(mTvShowContent = new TextView(getContext()));//动态添加view
        String selLabel = SPUtils.getInstance().getString(Constant.FLOAT_CHAR_KEY, getString(R.string.merits_add_tips));
        if (selLabel.equals(getString(R.string.empty_text))) {
            mTvShowContent.setText("");
        } else {
            mTvShowContent.setText(selLabel);
        }
        mTvShowContent.setTextSize(16);
        mTvShowContent.setTextColor(Color.WHITE);
        AnimatorSet animSet = new AnimatorSet();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(mTvShowContent, "translationX", 380, state);//移动到屏幕中间
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(mTvShowContent, "translationY", 300f, 0f);//从木鱼移动到上端
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(mTvShowContent, "alpha", 1f, 0f);//透明度变化
        AnimatorSet.Builder builder = animSet.play(anim2);
        builder.with(anim1).with(anim2).with(anim3);
        animSet.setDuration(3500);//持续时间
        animSet.start(); // 开始播放属性动画
    }

    private void getData() {
        List<WishBean> list = new ArrayList<>();
        list.add(new WishBean(R.drawable.aicon_cygg, getString(R.string.wish_name1), 128));
        list.add(new WishBean(R.drawable.aicon_thy, getString(R.string.wish_name2), 128));
        list.add(new WishBean(R.drawable.aicon_stjk, getString(R.string.wish_name3), 128));
        list.add(new WishBean(R.drawable.aicon_xyyc, getString(R.string.wish_name4), 128));
        list.add(new WishBean(R.drawable.aicon_fkbg, getString(R.string.wish_name5), 128));
        list.add(new WishBean(R.drawable.aicon_crpa, getString(R.string.wish_name6), 128));
        list.add(new WishBean(R.drawable.aicon_gzsl, getString(R.string.wish_name7), 128));
        list.add(new WishBean(R.drawable.aicon_qcsj, getString(R.string.wish_name8), 128));
        list.add(new WishBean(R.drawable.aicon_wsry, getString(R.string.wish_name9), 128));
        wishAdapter.setList(list);
    }

    private void setType() {
        if (type == 1) {
            mDataBinding.llFish.setVisibility(View.GONE);
            mDataBinding.llFunction.setVisibility(View.GONE);
            mDataBinding.rvWishList.setVisibility(View.VISIBLE);
            mDataBinding.tvFishMode.setText(getString(R.string.mode_name2));
        } else {
            mDataBinding.llFish.setVisibility(View.VISIBLE);
            mDataBinding.llFunction.setVisibility(View.VISIBLE);
            mDataBinding.rvWishList.setVisibility(View.GONE);
            if (type == 0) {
                mDataBinding.tvFishMode.setText(getString(R.string.mode_name1));
            } else if (type == 2) {
                mDataBinding.tvFishMode.setText(getString(R.string.mode_name3));
            } else if (type == 3) {
                mDataBinding.tvFishMode.setText(getString(R.string.mode_name4));
            }
        }
    }

    //选择模式弹窗
    private void selModeDialog() {
        mySelModeDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_mode, null);
        mySelModeDialog.setContentView(inflate);
        mySelModeDialog.setCancelable(true);
        Window dialogWindow = mySelModeDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView mode1 = inflate.findViewById(R.id.ivMode1);
        ImageView mode2 = inflate.findViewById(R.id.ivMode2);
        ImageView mode3 = inflate.findViewById(R.id.ivMode3);
        ImageView mode4 = inflate.findViewById(R.id.ivMode4);
        mode1.setOnClickListener(this);
        mode2.setOnClickListener(this);
        mode3.setOnClickListener(this);
        mode4.setOnClickListener(this);
    }

    private void getWoodenFishIconData() {
        List<Integer> woodenFishList = new ArrayList<>();
        woodenFishList.add(R.drawable.aicon_my1);
        woodenFishList.add(R.drawable.aicon_my2);
        woodenFishList.add(R.drawable.aicon_my3);
        woodenFishList.add(R.drawable.aicon_my4);
        woodenFishList.add(R.drawable.aicon_my5);
        woodenFishList.add(R.drawable.aicon_my6);
        woodenFishList.add(R.drawable.aicon_my7);
        woodenFishList.add(R.drawable.aicon_my8);
        int selIcon = SPUtils.getInstance().getInt(Constant.WOODEN_FISH_KEY, 0);
        mDataBinding.ivWoodenFish.setImageResource(woodenFishList.get(selIcon));
    }

}